package com.dmitriyp.movie.console.actions;

import static java.lang.System.out;

import java.util.HashSet;
import java.util.Set;

import com.dmitriyp.movie.console.AbstractUserAction;
import com.dmitriyp.movie.console.UserInputUtil;
import com.dmitriyp.movie.dao.IMovieManager;
import com.dmitriyp.movie.mapping.Format;
import com.dmitriyp.movie.mapping.Movie;

public class UserAddAction extends AbstractUserAction {


    public UserAddAction(IMovieManager manager) {
        super(manager);
    }

    public void doAction() {
        Movie movie = new Movie();
        out.print("Enter title: ");
        String value = scanner.next();
        movie.setTitle(value);

        out.print("Enter Release Year: ");
        int yearValue = UserInputUtil.readInt(scanner);
        movie.setReleaseYear(yearValue);

        out.println("Stars >> (Enter \'exit\' to finish)");
        Set<String> stars = inputStarsName();
        movie.setStars(stars);

        Format format = choseFormat();
        movie.setFormat(format);

        out.print("Add Movie: " + movie + "?(\'y\' - yes)");
        value = scanner.next();
        if ("y".equals(value.toLowerCase()))
            getManager().add(movie);
    }

    private Set<String> inputStarsName() {
        Set<String> stars = new HashSet<String>();
        while (true) {
            String value = scanner.next();
            if ("exit".equals(value.toLowerCase()))
                return stars;
            stars.add(value);
        }
    }

    private Format choseFormat() {
        while (true) {
            out.println("Formats:");
            for (Format format : Format.values()) {
                out.println(format.ordinal() + " - " + format.getName());
            }
            int ordinal = UserInputUtil.readInt(scanner);
            try {
                return Format.values()[ordinal];
            } catch (IndexOutOfBoundsException ex) {
                out.println("Incorrect index");
                // scanner.next();
            }
        }
    }
}
